package com.huaxinkaiye.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.huaxinkaiye.R;
import com.huaxinkaiye.application.HuaXinApplication;
import com.huaxinkaiye.bean.PictureInfo;
import com.huaxinkaiye.bean.RowsBean;
import com.huaxinkaiye.lookbigphoto.PhotosDialog;
import com.huaxinkaiye.utils.FileImageUpload;
import com.huaxinkaiye.utils.ImageUtils;
import com.huaxinkaiye.utils.OptionsUtil;
import com.huaxinkaiye.utils.PhotoImplActivity;
import com.huaxinkaiye.utils.ProgressUtil;
import com.huaxinkaiye.utils.SimpleClient;
import com.huaxinkaiye.utils.ToastUtil;
import com.huaxinkaiye.utils.UrlUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ShenPiDetailsActivity extends PhotoImplActivity implements
		OnClickListener, OnLongClickListener {
	public ImageView im_back, im_cancle, im_zhuangtai, im_che1, im_che2,
			im_che3;
	public TextView te_yes, te_no, te_username, te_who, te_zhuangtai, te_time,
			te_chulizhuangtai, te_jiage, te_chepai, te_xinghao,
			te_biaozhuncanzhi, te_yijialeixing;
	public EditText te_yijiajiner, ed_liyou;
	public RowsBean rowsBean;
	public Spinner sp_spinner;
	public ArrayList<String> picPathA;
	public ProgressUtil progress;
	public List<NameValuePair> params;
	public String localzqBigPicPath = "";
	public String localyhBigPicPath = "";
	public String localdjBigPicPath = "";
	public int zhaopianid;
	public JSONArray jsonarray;
	public int barginTypeid;
	public String s_type;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				Jiexileixing(msg.obj.toString());
				break;
			case 1:
				progress.dismiss();
				JiexisaveData(msg.obj.toString());
				break;
			case 3:
				progress.dismiss();
				Jiexiupload(msg.obj.toString());
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acticity_shenpidetails);
		progress = new ProgressUtil(this, "正在保存数据");
		initView();
		initData();
	}

	protected void Jiexiupload(String string) {
		// TODO Auto-generated method stub
		// zhaopianid
		Gson gson = new Gson();
		PictureInfo pinfo = gson.fromJson(string, PictureInfo.class);
		if (pinfo.getIsSuccess().equals("true")) {
			ToastUtil.show(this, pinfo.getMessage());
			if (zhaopianid == 1) {
				localzqBigPicPath =UrlUtils.host+pinfo.getPictureInfo().get(0).getPath();
				ImageLoader.getInstance().displayImage(localzqBigPicPath,
						im_che1, OptionsUtil.optionsAvatar);
			}
			if (zhaopianid == 2) {
				localyhBigPicPath = UrlUtils.host+pinfo.getPictureInfo().get(0).getPath();
				ImageLoader.getInstance().displayImage(localyhBigPicPath,
						im_che2, OptionsUtil.optionsAvatar);
			}
			if (zhaopianid == 3) {
				localdjBigPicPath = UrlUtils.host+pinfo.getPictureInfo().get(0).getPath();
				ImageLoader.getInstance().displayImage(localdjBigPicPath,
						im_che3, OptionsUtil.optionsAvatar);
			}
		} else {
			ToastUtil.show(this, pinfo.getMessage());
		}
	}

	protected void JiexisaveData(String string) {
		// TODO Auto-generated method stub
		Log.e("shenpi--", string);
		try {
			JSONObject json=new JSONObject(string);
			if(json.getString("isSuccess").equals("true")){
				ToastUtil.show(this,json.getString("message"));
				Intent intent=new Intent(this,DaiWoShenPiListActivity.class);
				setResult(RESULT_OK,intent);
				finish();
			}else{
				ToastUtil.show(this,json.getString("message"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void Jiexileixing(String string) {
		// TODO Auto-generated method stub
		Log.e("string--", string);
		ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		try {
			jsonarray = new JSONArray(string);
			for (int i = 0; i < jsonarray.length(); i++) {
				JSONObject json = new JSONObject(jsonarray.get(i).toString());
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("text", json.get("name").toString());
				data.add(map);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, data,
				R.layout.spinner, new String[] { "text" },
				new int[] { R.id.textView1 });
		// 设置显示的数据
		sp_spinner.setAdapter(simpleAdapter);
		Log.e("rowsBean.getBarginType().getMean()", rowsBean.getBarginType().getMean());
		int i = 0;
		if(rowsBean.getBarginType().getId()==96){
			sp_spinner.setSelection(0);	
			 i=0;
		}
		if(rowsBean.getBarginType().getId()==97){
			sp_spinner.setSelection(1);
			i=1;
		}
		if(rowsBean.getBarginType().getId()==98){
			sp_spinner.setSelection(2);
		     i=2;
		}
		// 注册事件
		sp_spinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
						Toast.makeText(getApplicationContext(), "没有改变的处理",
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						Spinner spinner = (Spinner) arg0;
						s_type=spinner
						.getItemAtPosition(arg2)
						.toString()
						.substring(
								6,
								spinner.getItemAtPosition(arg2)
										.toString().length() - 1)
						+ "";
//						te_yijialeixing.setText(spinner
//								.getItemAtPosition(arg2)
//								.toString()
//								.substring(
//										6,
//										spinner.getItemAtPosition(arg2)
//												.toString().length() - 1)
//								+ "");
					}
				});
	}

	private void initView() {
		// TODO Auto-generated method stub
		im_back = (ImageView) findViewById(R.id.im_back);
		im_back.setOnClickListener(this);
		im_cancle = (ImageView) findViewById(R.id.im_cancle);
		im_cancle.setOnClickListener(this);
		te_username=(TextView)findViewById(R.id.te_username);
		im_zhuangtai = (ImageView) findViewById(R.id.im_zhuangtai);
		te_who = (TextView) findViewById(R.id.te_who);
		te_zhuangtai = (TextView) findViewById(R.id.te_zhuangtai);
		te_time = (TextView) findViewById(R.id.te_time);
		te_chulizhuangtai = (TextView) findViewById(R.id.te_chulizhuangtai);
		te_jiage = (TextView) findViewById(R.id.te_jiage);
		te_chepai = (TextView) findViewById(R.id.te_chepai);
		te_xinghao = (TextView) findViewById(R.id.te_xinghao);
		te_biaozhuncanzhi = (TextView) findViewById(R.id.te_biaozhuncanzhi);
		//te_yijialeixing = (TextView) findViewById(R.id.te_yijialeixing);
		sp_spinner = (Spinner) findViewById(R.id.sp_spinner);
		te_yijiajiner = (EditText) findViewById(R.id.te_yijiajiner);
		ed_liyou = (EditText) findViewById(R.id.ed_liyou);
		im_che1 = (ImageView) findViewById(R.id.im_che1);
		im_che1.setOnClickListener(this);
		im_che1.setOnLongClickListener(this);
		im_che2 = (ImageView) findViewById(R.id.im_che2);
		im_che2.setOnClickListener(this);
		im_che2.setOnLongClickListener(this);
		im_che3 = (ImageView) findViewById(R.id.im_che3);
		im_che3.setOnClickListener(this);
		im_che3.setOnLongClickListener(this);
		te_yes = (TextView) findViewById(R.id.te_yes);
		te_yes.setOnClickListener(this);
		InitSpinnerData();
	}

	private void InitSpinnerData() {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
		String url = UrlUtils.yijialeixing_url;
		Log.e("yijialeixing_url", url);
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("", ""));
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				String data;
				try {
					data = SimpleClient.doPost(UrlUtils.yijialeixing_url,
							params);
					Log.e("yijialeixing_data", data);
					Message message = new Message();
					message.what = 0;
					message.obj = data;
					handler.sendMessage(message);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	} else {
		Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
	}
	}

	private void initData() {
		// TODO Auto-generated method stub
		rowsBean = (RowsBean) getIntent().getSerializableExtra("rowsBeanInfo");
		te_username.setText(rowsBean.getValueBarginRequestUser().getRealname()+"的申请");
		te_who.setText(rowsBean.getPlateNumber());
		te_zhuangtai = (TextView) findViewById(R.id.te_zhuangtai);
		if(rowsBean.getBarginAudit()==1){
			te_zhuangtai.setText("提交议价申请");
		}
		if(rowsBean.getBarginAudit()==2){
			te_zhuangtai.setText("提交议价审核");
		}
		if(rowsBean.getBarginAudit()==3){
			te_zhuangtai.setText("提交成交申请");
		}
		if(rowsBean.getBarginAudit()==4){
			te_zhuangtai.setText("提交成交审核");
		}
		if(rowsBean.getBarginAudit()==5){
			te_zhuangtai.setText("残值发放");
		}
		
		//te_time.setText(rowsBean.getBarginAudit());
		// te_chulizhuangtai.setText(rowsBean.getBarginType().getMean());
		// te_jiage.setText(rowsBean.getBarginAmount()+"");
		te_chepai.setText(rowsBean.getPlateNumber());
		te_xinghao.setText(rowsBean.getValueBrand().getCarType());
		te_biaozhuncanzhi.setText(rowsBean.getStandardSurplusValue() + "");
		// te_yijialeixing.setText(rowsBean.getBarginType().getMean());
		te_yijiajiner.setText(rowsBean.getBarginAmount()+"");
		ed_liyou.setText(rowsBean.getBarginComments());
		picPathA = new ArrayList<String>();
		for (int i = 0; i < rowsBean.getPictures().size(); i++) {
			if (rowsBean.getPictures().get(i).getFileType() == 14) {
				picPathA.add(UrlUtils.host
						+ rowsBean.getPictures().get(i).getFilepath());
			}
		}
		if (picPathA.size() == 1) {
			localzqBigPicPath = picPathA.get(0);
			ImageLoader.getInstance().displayImage(localzqBigPicPath, im_che1,
					OptionsUtil.optionsAvatar);
		}
		if (picPathA.size() == 2) {
			localzqBigPicPath = picPathA.get(0);
			localyhBigPicPath = picPathA.get(1);
			ImageLoader.getInstance().displayImage(localzqBigPicPath, im_che1,
					OptionsUtil.optionsAvatar);
			ImageLoader.getInstance().displayImage(localyhBigPicPath, im_che2,
					OptionsUtil.optionsAvatar);
		}
		if (picPathA.size() >= 3) {
			localzqBigPicPath = picPathA.get(0);
			localyhBigPicPath = picPathA.get(1);
			localdjBigPicPath = picPathA.get(2);
			ImageLoader.getInstance().displayImage(localzqBigPicPath, im_che1,
					OptionsUtil.optionsAvatar);
			ImageLoader.getInstance().displayImage(localyhBigPicPath, im_che2,
					OptionsUtil.optionsAvatar);
			ImageLoader.getInstance().displayImage(localdjBigPicPath, im_che3,
					OptionsUtil.optionsAvatar);
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.im_back:
			Intent intent=new Intent(this,DaiWoShenPiListActivity.class);
			setResult(RESULT_OK,intent);
			finish();
			break;
		case R.id.im_cancle:
			Intent intent2=new Intent(this,DaiWoShenPiListActivity.class);
			setResult(RESULT_OK,intent2);
			finish();
			break;
		case R.id.im_che1:
			// 查看大图
			if (localzqBigPicPath.equals("")) {
				ToastUtil.show(this, "没有图片");
				return;
			}
			lookBigImage(localzqBigPicPath);
			break;
		case R.id.im_che2:
			// 查看大图
			if (localyhBigPicPath.equals("")) {
				ToastUtil.show(this, "没有图片");
				return;
			}
			lookBigImage(localyhBigPicPath);
			break;
		case R.id.im_che3:
			// 查看大图
			if (localdjBigPicPath.equals("")) {
				ToastUtil.show(this, "没有图片");
				return;
			}
			lookBigImage(localdjBigPicPath);
			break;
		case R.id.te_yes:
			shenpi();
			break;
		}
	}

	private void shenpi() {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
		for (int i = 0; i < jsonarray.length(); i++) {
			JSONObject json;
			try {
				json = new JSONObject(jsonarray.get(i).toString());
				if (json.getString("name").equals(s_type)) {
					barginTypeid = json.getInt("id");
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Log.e("barginTypeid", barginTypeid + "");
		progress.show();
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id", rowsBean.getId() + ""));
		params.add(new BasicNameValuePair("barginType.id", barginTypeid + ""));
		params.add(new BasicNameValuePair("barginAmount", te_yijiajiner
				.getText().toString()));
		params.add(new BasicNameValuePair("barginComments", ed_liyou.getText()
				.toString()));
		params.add(new BasicNameValuePair("barginAudit", "2"));
		
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				String data;
				try {
					data = SimpleClient.doPost(UrlUtils.barginrequest_saveandsubmit_url, params);
					Log.e("shenpi_data", data);
					Message message = new Message();
					message.what = 1;
					message.obj = data;
					handler.sendMessage(message);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	} else {
		Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
	}
	}

	protected void lookBigImage(String s) {
		// TODO Auto-generated method stub
		final ArrayList<String> urllist = new ArrayList<String>();
		urllist.add(s);
		new PhotosDialog(this, R.style.Dialog).show(0, urllist);
	}

	@Override
	public boolean onLongClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.im_che1:
			zhaopianid = 1;
			showPopupMenu(im_che1, false,"other");
			break;
		case R.id.im_che2:
			zhaopianid = 2;
			showPopupMenu(im_che2, false,"other");
			break;
		case R.id.im_che3:
			zhaopianid = 3;
			showPopupMenu(im_che3, false,"other");
			break;
		}
		return true;
	}

	@Override
	public void doAfterZoom(Bitmap bitmap) {
		// TODO Auto-generated method stub
		if (zhaopianid == 1) {
			im_che1.setImageBitmap(bitmap);
		} else if (zhaopianid == 2) {
			im_che2.setImageBitmap(bitmap);
		} else {
			im_che3.setImageBitmap(bitmap);
		}
		String localPicPath = ImageUtils.savePicToCache(this, bitmap);
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id", rowsBean.getId() + ""));
		params.add(new BasicNameValuePair("fileType", "14"));
		params.add(new BasicNameValuePair("pictureFile", localPicPath));
		final String url = UrlUtils.picture_url;
		if (HuaXinApplication.isNetWorkConnected()) {
		progress.show();
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				String result = FileImageUpload.postFile(url, params);
				Log.e("shenpiupload_result", result);
				Message message = new Message();
				message.what = 3;
				message.obj = result;
				handler.sendMessage(message);
			}
		}.start();
	} else {
		Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
	}
	}
}
